import axios, {type AxiosResponse} from "axios";
import {ElMessage} from "element-plus";
import {useAdminStore} from "@/stores/admin.ts";
import router from "@/router";
import {useMemberStore} from "@/stores/member.ts";

// axios 实例（管理员）
const adminRequest = axios.create({
    // 基础路径
    baseURL: 'http://localhost:8080',
    timeout: 5000   // 超时时间
})

// axios 实例（用户）
const userRequest = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000
});

// 请求拦截器（管理员）
adminRequest.interceptors.request.use((config) => {
    const adminStore = useAdminStore()
    if (adminStore.adminInfo.token) {
        config.headers.token = adminStore.adminInfo.token
    }
    return config
})

// 请求拦截器（用户）
userRequest.interceptors.request.use((config) => {
    const memberStore = useMemberStore()
    if (memberStore.memberInfo.token) {
        config.headers.token = memberStore.memberInfo.token
    }
    return config
})

// 响应拦截器
adminRequest.interceptors.response.use((response) => {
    return response.data
},  async (error) => {
    if (error.response && error.response.status === 401) {
        // 清除token
        const adminStore = useAdminStore()
        await adminStore.adminLogout()

        await router.push('/adminLogin')
        ElMessage.error('登录已过期，请重新登录')
    } else {
        ElMessage.error(error.message)
    }
    return Promise.reject(error)
})

userRequest.interceptors.response.use((response) => {
    return response.data
}, async (error) => {
    if (error.response && error.response.status === 401) {
        const  memberStore = useMemberStore()
        await memberStore.memberLogout()

        await router.push('/memberLogin')
        ElMessage.error('登录已过期，请重新登录')
    } else {
        ElMessage.error(error.message)
    }
    return Promise.reject(error)
})

// 对外暴露
export {adminRequest, userRequest}